package com.hopu.petshop.controller.old;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

@WebServlet("/download.do")
public class DownloadServlet extends HttpServlet {

    public static final String PATH = "D:\\";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String filename = req.getParameter("filename");
        //设置响应头 实现下载框出现
        resp.setHeader("content-disposition",
                "attachment;filename=" + URLEncoder.encode(filename,"UTF-8"));
        //创建文件输入流
        try(InputStream in = new FileInputStream(PATH + filename);
            ServletOutputStream out = resp.getOutputStream();) {
            byte[] buffer = new byte[1024];
            int len = 0;
            //读取文件，写入到客户端的输出流中
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            System.out.println(filename+"下载完成！");
        }catch (IOException ex){
            ex.printStackTrace();
        }
    }
}
